//
//  YTLoginViewController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/9.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTLoginViewController.h"
#import <UMShare/UMShare.h>

#define kCornRadius 5

@interface YTLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *verfyMoblieButton;
@property (weak, nonatomic) IBOutlet UIView *securContentView;           // 验证码内容视图

@property (weak, nonatomic) IBOutlet UIView *phoneContentView;       // 手机号内容视图
@property (weak, nonatomic) IBOutlet UIImageView *warnImageView;

@property (weak, nonatomic) IBOutlet UIView *otherPlatformView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxtField;    // 手机号txtfield
@property (weak, nonatomic) IBOutlet UIButton *wechatButton;


@property (weak, nonatomic) IBOutlet UITextField *securityCodeTxtField;     // 验证码txtfield

@property (weak, nonatomic) IBOutlet JKCountDownButton *getCodeButton;   // 获取验证码按钮

@property (weak, nonatomic) IBOutlet UIButton *loginButton; // 登录按钮

@property (weak, nonatomic) IBOutlet UILabel *forgetLabel; // 忘记密码LAbel

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoHeightCons;


@property(nonatomic ,strong)UMSocialUserInfoResponse *wechatAccount;

@end

@implementation YTLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupUI];
    
    self.logoHeightCons.constant = iPhone5 ? 74 : 120;
    
    [self.view layoutIfNeeded];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetLabelClick)];
    [self.forgetLabel addGestureRecognizer:tap];
    
    [self.phoneTxtField addTarget:self
                           action:@selector(verfyPhoneTxt:)
                 forControlEvents:UIControlEventEditingChanged];
}

#pragma mark: - 手机号txtfield监听
- (void)verfyPhoneTxt:(UITextField *)textField
{
    self.verfyMoblieButton.selected = [textField.text phoneNumberIsTrue];
}


#pragma mark: - 微信登录 按钮监听
- (IBAction)wechatLoginClick
{
    [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
}


#pragma mark: - 微信登录SSO 方法
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType
                                        currentViewController:nil
                                                   completion:^(id result, NSError *error)
     {
        if (error) {
            NSLog(@"%@",error);
            [self.view showErrorWithTipStr:@"登录失败"];
        }else{
            
            UMSocialUserInfoResponse *resp = result;
            // 第三方登录数据(为空表示平台未提供)
            self.wechatAccount = resp;
            [YTNetworkManager.shareManager requestWechatLoginWithWechat_uuid:resp.uid
                                                                  completion:^(BOOL isSucc, BOOL isBindMoblie, NSString *error)
             {
                 if (!isSucc) {
                     [self.view showErrorWithTipStr:error];
                     return ;
                 }
                 
                 // 未绑定手机
                 if (!isBindMoblie) {
                     
                     self.navigationItem.title = @"账户安全";
                     self.loginButton.selected = YES;
                     self.forgetLabel.text = @"为了账户安全, 请关联手机号";
                     self.warnImageView.hidden = false;
                     self.otherPlatformView.hidden = YES;
                     self.wechatButton.hidden = YES;
                     self.forgetLabel.textColor = kMainColor;
                     
                 }else{
                     [self.view showAwardWithTipStr:@"登录成功"];
                  
                     [self backButtonClick];
                 }
                 
             }];

            
            
        }
    }];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"YTLoginViewController" bundle:nil];
        self = [sb instantiateViewControllerWithIdentifier:@"loginID"];
    }
    return self;
}
#pragma mark: - 登录按钮监听
- (IBAction)loginButtonClick:(UIButton *)sender
{
        if (!self.phoneTxtField.hasText) {
            [self.view showTipWithTipStr:@"请输入手机号"];
            return;
        }
        if (!self.securityCodeTxtField.hasText) {
            [self.view showTipWithTipStr:@"请输入验证码"];
            return;
        }
    
    
    // 绑定手机号
    if (sender.selected)
    {
        [YTNetworkManager.shareManager requestBindPhoneWithWechat_uuid:self.wechatAccount.uid
                                                                 phone:self.phoneTxtField.text
                                                                  code:self.securityCodeTxtField.text
                                                            completion:^(BOOL isSucc, NSString *error)
        {
            // 失败
            if (!isSucc) {
                [self.view showTipWithTipStr:error];
                return ;
            }
         
            
            [self.view showAwardWithTipStr:@"登录成功"];
            // success
            if ([self.showTipDelegate respondsToSelector:@selector(loginVCShowTip:tip:)]) {
                [self.showTipDelegate loginVCShowTip:self tip:error];
            }
            [self.navigationController popViewControllerAnimated:true];
        }];
        
    }else{
        [YTNetworkManager.shareManager requestLoginOrRegistWithPhone:self.phoneTxtField.text
                                                                code:self.securityCodeTxtField.text
                                                          completion:^(BOOL isSucc, NSString *error)
         {
             // 失败
             if (!isSucc) {
                 [self.view showTipWithTipStr:error];
                 return ;
             }
             
             
             
             // success
             if ([self.showTipDelegate respondsToSelector:@selector(loginVCShowTip:tip:)]) {
                 [self.showTipDelegate loginVCShowTip:self tip:error];
             }
             [self.navigationController popViewControllerAnimated:true];
         }];
    }
}

#pragma mark: - 提示用户的方法

// 设置界面
- (void)setupUI
{

    self.getCodeButton.layer.masksToBounds = YES;
    self.getCodeButton.layer.cornerRadius = 2;
    // 获取验证码按钮 边线
    self.getCodeButton.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.getCodeButton.layer.borderWidth = 1;
    
    // 登录按钮圆角
    self.loginButton.layer.masksToBounds = YES;
    self.loginButton.layer.cornerRadius = kCornRadius;
    
    // navTitle
    self.navigationItem.title = @"登录注册";
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                             initWithImage:[UIImage dh_setNavImageName:@"倛袨1"]
                                             style:UIBarButtonItemStylePlain
                                             target:self
                                             action:@selector(backButtonClick)];
  
}

#pragma mark: - 返回按钮 监听
- (void)backButtonClick
{
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark: - 获取验证码 按钮监听
- (IBAction)getVerifyBtnClick:(JKCountDownButton *)sender
{
    if (!self.verfyMoblieButton.selected) {
        [self.view showTipWithTipStr:@"请输入正确的手机号"];
        return;
    }
    
    sender.enabled = YES;
    //button type要 设置成custom 否则会闪动
    [sender startCountDownWithSecond:60];
    
    // 获取当前时间错
    NSString *timestamp = [NSString getNowTime];
    // 生成签名
    NSString *sign = [[NSString stringWithFormat:@"%@%@%@%@",kGetVerifiCodeKey,timestamp,self.phoneTxtField.text,self.loginButton.selected ? @"3" : @"1"] md5];
    
    // 发送验证码
    [YTNetworkManager.shareManager requestVerifyCodeWithMobile:self.phoneTxtField.text
                                                          type:self.loginButton.selected ? @"3" : @"1"
                                                        timestamp:timestamp
                                                          sign:sign
                                                    completion:^(BOOL isSucc, NSString *statusInfo)
    {
        if (!isSucc) {
            [self.view showTipWithTipStr:statusInfo];
            sender.enabled = NO;
            return ;
        }
        
        [self.view showTipWithTipStr:statusInfo];
        sender.enabled = NO;
        
    }];
    
    [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
        NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
        return title;
    }];
    
    [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
        countDownButton.enabled = YES;
        return @"点击重新获取";
    }];
}
#pragma mark: - 用户注册协议 按钮监听
- (IBAction)userProtocolButtonClick
{
    YTMineWebController *webVC = [[YTMineWebController alloc] init];
    webVC.url = [NSString stringWithFormat:@"%@InvitingFriends/registrationAgreement",kTestMainUrl];
    webVC.title = @"用户协议";
    [self.navigationController pushViewController:webVC animated:true];
}

// 设置内容视图样式
- (void)setUIWIthContentView:(UIView *)view
{
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = kCornRadius;
    view.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    view.layer.borderWidth = 1;
}



#pragma mark: - 忘记密码监听
- (void)forgetLabelClick
{
    NSLog(@"点到了");
}


// touchesBegan
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
@end
